package com.cn.goodsadmin.common;


import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.type.Type;
import org.springframework.orm.hibernate5.HibernateCallback;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PageQueryCallback implements HibernateCallback {

	private PageQueryCondition queryCondition = null;

	public PageQueryCallback(PageQueryCondition queryCondition) {
		this.queryCondition = queryCondition;
	}

	public Object doInHibernate(Session session) throws HibernateException {
		if (log.isDebugEnabled()) {
			log.debug("doInHibernate(Session) - start");
		}
		Query queryObject = session.createQuery(this.queryCondition.getQueryString());
		Object[] values = this.queryCondition.getObjArray();
		Type[] types = this.queryCondition.getTypeArray();

		if (values != null) {
			for (int i = 0; i < values.length; ++i) {
				if (log.isDebugEnabled()) {
					log.debug("i=" + i);
					log.debug("values[i]=" + values[i]);
					if (types != null)
						log.debug("types[i]=" + types[i]);
				}
				if (types != null)
					queryObject.setParameter(i, values[i], types[i]);
				else {
					queryObject.setParameter(i, values[i]);
				}
			}
		}

		ScrollableResults sr = null;
		try {
			PageQueryResult queryResult = new PageQueryResult();
			queryResult.setQueryResult(new ArrayList());
			queryResult.setTotalCount(0);

			sr = queryObject.scroll();
			PageQueryResult localPageQueryResult1;
			if (!(sr.last()))
			{
				if (log.isDebugEnabled()) {
					log.debug("doInHibernate(Session) - end");
				}
				localPageQueryResult1 = queryResult;
				return localPageQueryResult1;
			}

			int totalCount = sr.getRowNumber();
			queryResult.setTotalCount(totalCount + 1);

			int pageSize = this.queryCondition.getPageSize();
			int pageIndex = this.queryCondition.getPageIndex() - 1;

			int startRowNum = pageIndex * pageSize;
			if (!(sr.setRowNumber(startRowNum))) {
				if (log.isDebugEnabled()) {
					log.debug("doInHibernate(Session) - end");
				}
				localPageQueryResult1 = queryResult;
				return localPageQueryResult1;
			}

			List list = queryResult.getQueryResult();
			for (int i = 0; i < pageSize; ++i) {
				list.add(sr.get());
				if (!(sr.next())) {
					break;
				}
			}

			if (log.isDebugEnabled()) {
				log.debug("doInHibernate(Session) - end");
			}
			return queryResult;
		} finally {
			if (sr != null)
				sr.close();
		}
	}
}
